package com.md.common.utils.web.auth.token;

import com.md.common.utils.web.auth.BaseCodeUtil;
import com.md.common.utils.web.auth.token.exception.TokenInvalidException;
import org.apache.commons.lang3.StringUtils;

/**
 * 功能描述：会员访问token
 *
 * @author lujianping@oak168.com
 * @version 1.0
 * @date 2018-7-16 10:46
 * @since JDK 1.8
 */
public class AccessToken {
    private String token;
    /**
     * token生成时间
     */
    private Long tokenTime;
    /**
     * token过期时间，单位秒，大概1小时
     */
    public static int tokenExpireTime = 2 * 60 * 60;

    /**
     * 生成token
     * @return
     */
    public String genToken(){
        long tokenTime = System.currentTimeMillis();
        String timestamp = StringUtils.reverse(BaseCodeUtil.encodeLongBase64(tokenTime));
        timestamp = BaseCodeUtil.encodeStringBase64(timestamp);
        //混入userId
        return BaseCodeUtil.encodeStringBase64(timestamp);
    }

    /**
     * token解析
     * @throws TokenInvalidException
     */
    public void extract() throws TokenInvalidException {
        if (StringUtils.isBlank(this.token)) {
            throw new TokenInvalidException();
        }
        String tokenStr = BaseCodeUtil.decodeStringBase64(this.token);
        if (StringUtils.isNotBlank(tokenStr)) {
            this.tokenTime = BaseCodeUtil.decodeLongBase64(StringUtils.reverse(tokenStr));
        }
    }

    /**
     * 判断token是否过期
     * @return
     */
    public boolean isExpired(){
        return ((System.currentTimeMillis() - this.tokenTime)/1000) > tokenExpireTime;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public Long getTokenTime() {
        return tokenTime;
    }

    public void setTokenTime(Long tokenTime) {
        this.tokenTime = tokenTime;
    }

    public static int getTokenExpireTime() {
        return tokenExpireTime;
    }

    public static void setTokenExpireTime(int tokenExpireTime) {
        AccessToken.tokenExpireTime = tokenExpireTime;
    }
}
